/*
 *
 *  Copyright (C) 2010 Tal Eisenberg
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package tal.drivechain.misc;

import java.util.ArrayList;
import java.util.Hashtable;

/**
 * group property - the greatest value of a property in any of the group members
 * @author eisental
 */
public class Group extends ArrayList<GroupMember> {

    /** a list of properties*/
    protected Hashtable<String, Object> properties = new Hashtable<String, Object>();

    public void addMember(GroupMember member) {
        if (!contains(member)) {
            add(member);
            member.setGroup(this);
            updateProperties(member);
        }

    }

    public void removeMember(GroupMember member) {
        String[] props = member.getGroupProperties();
        remove(member);
        for (String prop : props) updateProperty(prop);
    }

    /**
     * reevalute all the properties that this GroupMember supports.
     */
    public void updateProperties(GroupMember m) {
        for (String prop : m.getGroupProperties()) {
            updateProperty(prop);
        }
    }

    /**
     * reevaluate a single property.
     * 
     * @param property
     */
    public void updateProperty(String property) {
        Comparable value = null;
        for (GroupMember m : this) {
            if (m.hasProperty(property)) {
                Comparable mvalue = m.getGroupPropertyState(property);
                if (value==null || mvalue.compareTo(value)>0) {
                    value = mvalue;
                }
            }
        }
        if (value==null) //remove property
            properties.remove(property);
        else
            properties.put(property, value);
    }

    public Object getGroupProperty(String property) {
        return properties.get(property);
    }

    public Hashtable<String,Object> getAllProperties() {
        return properties;
    }

}
